//
//  AppDelegate.m
//  Challenge
//
//  Created by 王桂敏 on 2017/1/13.
//  Copyright © 2017年 王桂敏. All rights reserved.
//

#import "AppDelegate.h"
#import "SetRootViewControllerHandle.h"
#import <BuglyHotfix/Bugly.h>
#import <BuglyHotfix/BuglyLog.h>
#import <BuglyHotfix/BuglyConfig.h>
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "NSObject+NetworkingState.h"

@interface AppDelegate ()<NetworkingHandleDelegate,UIAlertViewDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (void)dealloc{
    
    [self removeObserver:self name:kNotificationFirstNetwork object:nil];
    [self removeObserver:self name:kNotificationNetState object:nil];
    [self removeObserver:self];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.launchOptions = launchOptions;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //  极光推送初始化
    [self initPushWithOptions:launchOptions];
    [self addObserver:self selector:@selector(firstNetworkAction) name:kNotificationFirstNetwork object:nil];
    //  设置界面
    [self initWith:launchOptions application:application];
    
    //检查是否强制更新
    [self checkAppVersion];
    
    [self addBugly];
    //网络网络监听
    [self initReachability];
    return YES;
}

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.allowRotation) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }
    
    return UIInterfaceOrientationMaskPortrait;
    
}

- (void)initReachability{
    
    [self changeNetworkState];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:kNotificationNetState
                                               object:nil];
    
    
    
}



- (void)networkChanged:(NSNotification *)notification {
    
    if (self.netState == AFNetworkReachabilityStatusReachableViaWWAN || self.netState == AFNetworkReachabilityStatusUnknown) {
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self showWarningWithStatus:@"当前使用的是移动网络"];
            
        });
    }
    
}



//检查更新
-(void)checkAppVersion
{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObject:@"1" forKey:@"type"];
    [[NetworkManager manager] postWithURL:NET_LatestVersionIndex param:param delegate:self isEncrypt:NO type:NetWorkingType3];
}
#pragma mark 设置界面
- (void)initWith:(NSDictionary *)launchOptions application:(UIApplication *)application{
    SetRootViewControllerHandle *hanlde = [[SetRootViewControllerHandle alloc] init];
    [hanlde setRootViewController];
    
}

- (void)addBugly
{
    //Bugly
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.blockMonitorEnable = YES;
#ifdef DEBUG
    config.hotfixEncryptEnable = NO;//js传输是否加密
    config.hotfixDebugMode = YES;//是否使用本地补丁
    config.debugMode = YES;
#else
    config.hotfixEncryptEnable = YES;
    config.hotfixDebugMode = NO;
    config.debugMode = NO;
#endif
    
    [Bugly startWithAppId:Bugly_AppId
#ifdef DEBUG
        developmentDevice:YES
#endif
                   config:config];
    [Bugly setTag:Bugly_SceneTag];//测试Or发布阶段
    if (self.isLogin) {
        [Bugly setUserIdentifier:[NSString stringWithFormat:@"%@(%@)【%@】",self.nickName,self.phone,[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
    }
    else{
        [Bugly setUserIdentifier:[NSString stringWithFormat:@"!!!未登录状态!!!【%@】",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
    }
#ifdef DEBUG
    [BuglyLog initLogger:BuglyLogLevelWarn consolePrint:YES];
#endif
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark 极光推送初始化
- (void)initPushWithOptions:(NSDictionary *)launchOptions{
    // 1. 注册APNS类型
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // 2. 初始化极光
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    
    /**如果属于DEBUG模式开启日志模式**/
#ifdef   DEBUG
    [JPUSHService setDebugMode];
#else
    [JPUSHService setLogOFF];
#endif
    
    
    // 4. 处理透传消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMsg:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    // 5. 获取registrationID(监听kJPFNetworkDidLoginNotification)
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didRegister) name:kJPFNetworkDidRegisterNotification object:nil];
    //  登录成功
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didReceiveRegisterId:) name:kJPFNetworkDidLoginNotification object:nil];
    
    
}
- (void)didRegister{
    self.firstNetwork = YES;
}
- (void)firstNetworkAction{
    [self initPushWithOptions:self.launchOptions];
}
- (void)didReceiveRegisterId:(NSNotification *)notification {
    
    //    NSString *pushToken = [JPUSHService registrationID];
    //    self.registrationID = pushToken;
    
    
}
/**
 *  获取自定义消息推送内容
 *
 */
- (void)didReceiveMsg:(NSNotification *)notification {
    
}
// IOS 7 Support Required
//  接受到APN消息的通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    // remote notification handler
    // 处理收到的APNS消息，向服务器上报收到APNS消息
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    [self receivePushMessage:userInfo];
    
}

//  Required
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    
    // remote notification handler
    // 处理收到的APNS消息，向服务器上报收到APNS消息
    [JPUSHService handleRemoteNotification:userInfo];
    
    [self receivePushMessage:userInfo];
    
}
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
}
#pragma mark- JPUSHRegisterDelegate
#pragma mark - iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)
#pragma mark- JPUSHRegisterDelegate
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center
        willPresentNotification:(UNNotification *)notification
          withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self receivePushMessage:userInfo];
        
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);   // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self receivePushMessage:userInfo];
        
    }
    completionHandler();  // 系统要求执行这个方法
}

#endif
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)receivePushMessage:(NSDictionary *)userInfo{
    CustumTabBarController *TBC = (CustumTabBarController *)self.window.rootViewController;
    TBC.selectedIndex = 1;
}




- (void)networkingHandleSuccess:(NetworkingHandle *)handle parameters:(NSDictionary *)parameters responseObject:(id)responseObject type:(NetWorkingType)type{
    switch (type) {
        case NetWorkingType3:{
#ifdef DEBUG
            NSString *upVersion = [[responseObject[@"innerversionCode"] description] stringByReplacingOccurrencesOfString:@"." withString:@""];
            
#else
            NSString *upVersion = [[responseObject[@"outterversionCode"] description] stringByReplacingOccurrencesOfString:@"." withString:@""];
#endif
            NSInteger isUpdate = [responseObject[@"isUpdate"] integerValue];
            NSString *locationVersion = [[ApplyUntil version] stringByReplacingOccurrencesOfString:@"." withString:@""];
            
            if ([locationVersion integerValue] < [upVersion integerValue]) {
                
                if (isUpdate) {
                    __weak typeof(self) weakSelf = self;
                    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        [weakSelf removeUserLoginInfo];
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:AppStore_URLString]];
                        exit(0);
                        
                    }];
                    [self showMessageWithTitle:@"更新提示" message:@"为了让您获得更好的体验，您现在需要前往AppStore更新到最新版本!\n\n（注：如果反复提示更新，请尝试连续快速点按AppStore底部“更新”按钮，直至页面重新加载后，确认App是否更新成功?！）" actionArray:@[doneAction] VC:_window.rootViewController preferredStyle:UIAlertControllerStyleAlert];
                }else{
                    
                    if ([upVersion isEqualToString:[[TMCache sharedCache]objectForKey:KEY_OldVersion]]) break;
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [[TMCache sharedCache] setObject:upVersion forKey:KEY_OldVersion];
                        
                    }];
                    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        [[UIApplication sharedApplication]  openURL:[NSURL URLWithString:AppStore_URLString]];
                        
                    }];
                    [self showMessageWithTitle:@"更新提示" message:@"为了让您获得更好的体验，您现在需要前往AppStore更新到最新版本!\n\n（注：如果反复提示更新，请尝试连续快速点按AppStore底部“更新”按钮，直至页面重新加载后，确认App是否更新成功?！）" actionArray:@[cancelAction,doneAction] VC:_window.rootViewController preferredStyle:UIAlertControllerStyleAlert];
                }
                
            }
        }
            break;
        default:
            break;
    }
    
}
- (void)networkingHandleWarning:(NetworkingHandle *)handle responseObject:(id)responseObject type:(NetWorkingType)type{
    
    switch (type) {
        case NetWorkingType0:
        {
        }
            break;
        case NetWorkingType1:
        {
            if ([responseObject[@"returnNo"] isEqualToString:@"0032"]) {
                
                UIAlertController *alertV = [UIAlertController alertControllerWithTitle:@"提示" message:responseObject[@"returnInfo"] preferredStyle:UIAlertControllerStyleAlert];
                
                __weak typeof(self) weakSelf = self;
                
                UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [weakSelf removeUserLoginInfo];
                    
                }];
                
                [alertV addAction:done];
                
                [self.window.rootViewController presentViewController:alertV animated:YES completion:nil];
            }
        }
            break;
            
            
        default:
            break;
    }
    
}
- (void)networkingHandlefail:(NetworkingHandle *)handle type:(NetWorkingType)type{
    
}



@end
